package com.github.shiqiyue.app.api.sapi.controller.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.shiqiyue.app.api.sapi.common.SApiBaseController;
import com.github.shiqiyue.app.api.sapi.req.department.DepartmentAddReq;
import com.github.shiqiyue.app.api.sapi.req.department.DepartmentEditReq;
import com.github.shiqiyue.app.api.sapi.result.department.DepartmentTreeDTO;
import com.github.shiqiyue.app.common.constants.GlobalConstants;
import com.github.shiqiyue.app.common.entity.TreeNode;
import com.github.shiqiyue.app.common.enums.DeletedEnum;
import com.github.shiqiyue.app.common.result.Result;
import com.github.shiqiyue.app.common.utils.TreeNodeUtils;
import com.github.shiqiyue.app.modules.sys.entity.Department;
import com.github.shiqiyue.app.modules.sys.service.IDepartmentService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/***
 *
 * @author wenyao.wu
 */
@RestController
@RequestMapping("sapi/sys/department")
public class SApiDepartmentController extends SApiBaseController {

    @Autowired
    private IDepartmentService departmentService;

    /***
     * 部门列表
     * @return
     */
    @PreAuthorize("hasAuthority('0020100')")
    @PostMapping("list")
    public Result<List<TreeNode>> departmentList() {
        // 获取所有有效的权限（按钮）
        List<Department> departmentList = departmentService.list(new QueryWrapper<Department>());
        // 转换为vo
        List<DepartmentTreeDTO> departmentTreeDTOList = departmentList
                .stream()
                .map(item -> DepartmentTreeDTO.newInstance(item))
                .collect(Collectors.toList());
        // 添加children属性
        List<TreeNode> treeNodeList = TreeNodeUtils.listToTree(departmentTreeDTOList);
        return Result.success(treeNodeList);
    }

    /***
     * 添加部门
     * @param departmentAddReq
     * @return
     */
    @PreAuthorize("hasAuthority('0020101')")
    @PostMapping("add")
    public Result addDepartment(@Valid DepartmentAddReq departmentAddReq, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Result.fail(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        if (!departmentAddReq.getPid().equals(GlobalConstants.TREE_TOP_PID)) {
            Department parentNode = departmentService.getById(departmentAddReq.getPid());
            if (parentNode == null) {
                return Result.fail("上级节点无效");
            }
        }
        Department department = new Department();
        department.setName(departmentAddReq.getName());
        department.setPid(departmentAddReq.getPid());
        department.setIsDeleted(DeletedEnum.NO_DEL);
        departmentService.save(department);
        return Result.success();
    }

    /***
     * 修改部门
     * @param departmentEditReq
     * @return
     */
    @PreAuthorize("hasAuthority('0020102')")
    @PostMapping("edit")
    public Result editDepartment(@Valid DepartmentEditReq departmentEditReq, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Result.fail(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }

        Department updateParam = new Department();
        updateParam.setId(departmentEditReq.getId());
        updateParam.setName(departmentEditReq.getName());
        departmentService.updateById(updateParam);
        return Result.success();
    }

    /***
     * 删除部门
     * @param id
     */
    @PreAuthorize("hasAuthority('0020103')")
    @ApiOperation("删除权限")
    @PostMapping("delete")
    public Result deleteDepartment(Long id) {
        departmentService.removeById(id);
        return Result.success();
    }



}
